package com.endava.spring_ioc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Connection with database. Lazy load instance.
 * 
 * @author acojocar
 * @since 26.07.2013
 * @version 1.0
 * 
 */
public class DataBase {

	private Statement statement;
	private ResultSet resultSet;
	private String userName;
	private String password;

	private static DataBase instance;
	protected static Connection connect;

	/**
	 * Constructor. Initialize and starts the connection with Data Base.
	 */
	protected DataBase() {
		connect = null;
		statement = null;
		resultSet = null;
		userName = "root";
		password = "root";

		try {
			startConnection();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Lazy load instance of Data Base.
	 * 
	 * @return a instance of Data Base
	 */
	public static synchronized DataBase getInstance() {
		if (instance == null) {
			instance = new DataBase();
		}
		return instance;
	}

	/**
	 * Starts the connection with Data Base.
	 * 
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	private void startConnection() throws SQLException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");
		connect = DriverManager.getConnection("jdbc:mysql://localhost/BankDB?",
				userName, password);
	}

	/**
	 * Close the connection with Data Base.
	 */
	public void close() {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
			if (statement != null) {
				statement.close();
			}
			if (connect != null) {
				connect.close();
			}
		} catch (Exception e) {
		}
	}

	/**
	 * Gets the connection.
	 * 
	 * @return the connection
	 */
	public Connection getDB() {
		return connect;
	}
}
